package com.sinotrans.admin.config.security;

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;

import de.codecentric.boot.admin.server.config.AdminServerProperties;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	private final String adminContextPath;

	public WebSecurityConfig(AdminServerProperties adminServerProperties) {
		this.adminContextPath = adminServerProperties.getContextPath();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
		successHandler.setTargetUrlParameter("redirectTo");
		successHandler.setDefaultTargetUrl(adminContextPath + "/");
		http.authorizeRequests()
				// 公共访问权限
				.antMatchers(adminContextPath + "/assets/**").permitAll().antMatchers(adminContextPath + "/actuator/**")
				.permitAll().antMatchers(adminContextPath + "/login").permitAll()
				.antMatchers(adminContextPath + "/logout").permitAll()
				// 身份验证
				.anyRequest().authenticated().and()
				// 配置登录和注销
				.formLogin().loginPage(adminContextPath + "/login").successHandler(successHandler).and().logout()
				.logoutUrl(adminContextPath + "/logout").and()
				// 启用HTTP-Basic
				.httpBasic();
	}
}